package cn.edu.hbwe.book.servlet.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.exception.LoginException;
import cn.edu.hbwe.book.service.UserService;

/**
 * Servlet implementation class UserLoginServlet
 */
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 调用service来判断用户名和密码是否正确
		UserService service = new UserService();
		try {
			User user = service.login(username, password);
			// 用户名和密码正确，判断用户是否激活
			if (user.getState() == 1) {
				request.getSession().setAttribute("user", user);
				// 用户为超级管理员，跳转到后台页面
				String role = user.getRole();
				if (role.equals("超级管理员")) {
					response.sendRedirect(request.getContextPath() + "/admin/login/home.jsp");
					return;
				} else {
					response.sendRedirect(request.getContextPath() + "/bookweb/myAccount.jsp");
					return;
				}
			}
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("login_message", e.getMessage());
			request.getRequestDispatcher("/bookweb/login.jsp").forward(request, response);
			return;
		}

	}

}
